package org.mj.im.server.netty.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.AttributeKey;
import org.mj.im.common.constants.IMConstants;
import org.mj.im.common.distribute.DistributeCacheService;
import org.mj.im.common.enums.IMCmdType;
import org.mj.im.common.model.IMSendInfo;
import org.mj.im.server.cache.UserChannelContextCache;
import org.mj.im.server.holder.SpringContextHolder;
import org.mj.im.server.netty.processor.MessageProcessor;
import org.mj.im.server.netty.processor.factory.MessageProcessorFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IMChannelHandler extends SimpleChannelInboundHandler<IMSendInfo> {

    private final Logger logger = LoggerFactory.getLogger(IMChannelHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, IMSendInfo imSendInfo) throws Exception {
        IMCmdType cmdType = IMCmdType.getByCode(imSendInfo.getCmd());
        if (cmdType == null){
            return;
        }
        MessageProcessor messageProcessor = MessageProcessorFactory.getProcessor(cmdType);
        messageProcessor.process(channelHandlerContext,messageProcessor.transFrom(imSendInfo.getData()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("exceptionCaught", cause);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // 检测读超时事件，此时客户端断开了连接。需要删除对应的channel。后续重连即可
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                AttributeKey<Long> userIdAttr = AttributeKey.valueOf(IMConstants.USER_ID);
                AttributeKey<Integer> terminalAttr = AttributeKey.valueOf(IMConstants.TERMINAL_TYPE);
                Long userId = ctx.channel().attr(userIdAttr).get();
                Integer terminal = ctx.channel().attr(terminalAttr).get();
                logger.info("IMChannelHandler.userEventTriggered|心跳超时.即将断开连接, userId:{}, 终端类型:{}", userId, terminal);
                ctx.channel().close();
            }
        }else{
            super.userEventTriggered(ctx,evt);
        }
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        logger.info("handlerAdded {}",ctx.channel().id().asLongText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        AttributeKey<Long> userIdAttr = AttributeKey.valueOf(IMConstants.USER_ID);
        Long userId = ctx.channel().attr(userIdAttr).get();
        AttributeKey<Integer> terminalAttr = AttributeKey.valueOf(IMConstants.TERMINAL_TYPE);
        Integer terminal = ctx.channel().attr(terminalAttr).get();
        ChannelHandlerContext cachedCtx = UserChannelContextCache.get(userId, terminal);
        // 防止异地误删
        if (cachedCtx != null && cachedCtx.channel().id() != ctx.channel().id()) {
            UserChannelContextCache.removeChannel(userId,terminal);
            DistributeCacheService cacheService = SpringContextHolder.getBean(IMConstants.DISTRIBUTED_CACHE_REDIS_SERVICE_KEY);
            String redisKey = String.join(IMConstants.REDIS_KEY_SPLIT, IMConstants.IM_USER_SERVER_ID, userId.toString(), terminal.toString());
            cacheService.delete(redisKey);
            logger.info("IMChannelHandler.handlerRemoved|断开连接, userId:{}, 终端类型:{}", userId, terminal);
        }
    }
}
